package com.ethannhu.todaynews.adapter

import android.provider.ContactsContract.Data
import androidx.viewpager2.widget.ViewPager2
import com.ethannhu.todaynews.util.DataUtil
import com.google.android.material.tabs.TabLayout

/**
 * 让 TabLayout 和 ViewPager 联合使用
 */
class TabLayoutViewPager2Mediator(
    private val indicator: TabLayout,
    private val pager: ViewPager2,
    private val config: ((indicator: TabLayout, pager: ViewPager2) -> Unit)? = null
) {
    //初始化 TabLayout 内容
    init {
        val adapterCount = DataUtil.categories.size
        for (i in 0 until adapterCount) {
            indicator.addTab(indicator.newTab().setText(DataUtil.categories[i].title), false)
        }
        indicator.selectTab(indicator.getTabAt(0))
    }

    //关联 TabLayout和 ViewPager2的选择关系
    fun attach() {
        config?.invoke(indicator, pager)
        pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                indicator.selectTab(indicator.getTabAt(position))
            }
        })

        indicator.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val index = tab.position
                if (pager.currentItem != index) {
                    pager.setCurrentItem(index, true)
                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })
    }


}